export default {
	name: "menus",
	data() {
		return {
			timer: null,
			showChildren: false,
			showChildrenButton: false,
			currentNode: null,
			removeNode: {},
			isRemove: false,
			menuArray: [],
			validate: true,
			disabledIds: ["1", "1-1"],
			lazyTreeRowId: "",
			options: {
				FontAwesome: false,
				ElementUI: false,
				eIcon: false,//自带的图标，来自阿里妈妈
				eIconSymbol: false,//是否开启彩色图标
				addIconList: [],
				removeIconList: []
			},
			rules: {
				name: [
					{required: true, message: "请输入菜单名称", trigger: "blur"}
				],
				title: [
					{required: true, message: "请输入中文菜单标题", trigger: "blur"}
				],
				titleEn: [
					{required: true, message: "请输入英文菜单标题", trigger: "blur"}
				],
				icon: [
					{required: true, message: "请输入菜单图标", trigger: "blur"}
				],
				path: [
					{required: true, message: "请输入菜单映射路由", trigger: "blur"}
				]
			}
		};
	},
	computed: {
		menuList() {
			if (Array.isArray(this.menuArray) && this.menuArray.length === 0) {
				this.menuArray = this.menuHandler.loadMenus();
			}
			return this.menuArray;
		},
		mainNode() {
			if (!this.currentNode) {
				if (this.envMode === "production") {
					this.currentNode = this.menuArray[0];
				} else {
					this.currentNode = this.menuArray[1];
				}
			}
			this.showChildrenButton = this.menuHandler.hasChildren(this.currentNode);
			//正常点击node显示信息
			return this.currentNode;
		},
		tableData() {
			if (this.showChildren) {
				return this.mainNode.children;
			}
		},
		menusNames() {
			return this.menuHandler.allMenuNames();
		}
	},
	updated() {
		this.$nextTick(() => {
			if (this.showChildren) {
				this.$refs.menusTable.doLayout();
			}
		});
	},
	methods: {
		appendMenu(node, data) {
			node.expanded = false;
			//菜单的最大层级为3
			if (data.hasChildren && node.level !== 3) {
				let newChild = {
					id: data.id + "-" + (data.children.length + 1),
					name: "New Node",
					title: "新建节点",
					titleEn: "New Node",
					icon: "el-icon-s-data",
					group: "common",
					level: node.level + 1,
					permission: 1,
					hasChildren: false,
					path: ""
				};
				data.children.push(newChild);
				this.setActivedKey(data, data.children.length - 1);
			}
		},
		appendMainMenu() {
			let newNode = {
				id: (this.menuArray.length + 1) + "",
				name: "New Node",
				title: "新建节点",
				titleEn: "New Node",
				icon: "el-icon-s-data",
				group: "common",
				level: 1,
				permission: 1,
				hasChildren: true,
				children: []
			};
			this.menuArray.push(newNode);
			this.setActivedKey(newNode, this.menuArray.length - 1);
		},
		editMenu(node, data) {
			if (!this.isRemove) {
				this.currentNode = data;
			} else {
				//针对删除菜单后显示被删除菜单信息，应显示其父菜单信息，重新加载父节点数据，重新调用父节点的展开方法
				this.removeNode.parent.loaded = false;
				this.removeNode.parent.expand();
				this.isRemove = false;
			}
			this.getActiveKey();
		},
		removeMenu(node, data) {
			this.isRemove = true;
			this.removeNode = node;
			if (node.level === 1) {
				this.updateData(this.menuArray, null, data.id);
				if (this.envMode === "production") {
					this.currentNode = this.menuArray[0];
				} else {
					this.currentNode = this.menuArray[1];
				}
			} else {
				const parentData = node.parent.data;
				const length = parentData.children.length;
				this.updateData(parentData.children, parentData, data.id);
				this.setActivedKey(parentData, length);
			}
		},
		updateData(array, parent, id) {
			if (parent && parent.level === 1 && array.length === 1) {
				this.isRemove = false;
				return;
			}
			const index = array.findIndex(d => d.id === id);
			array.splice(index, 1);
			if (array.length === 0) {
				parent.hasChildren = false;
				parent.children = null;
				parent.path = "";
			} else {//更新 array 每个元素编号
				this.sortMenuId(parent, array);
			}
		},
		setActivedKey(node, length) {
			if (this.validate) {
				this.currentNode = Object.assign({}, node);
				//全量更新缓存数据
				this.vuex("menus", this.menuArray);
				// 同步刷新当前页面
				if ((!node.hasChildren && length === 1) || (node.hasChildren && node.children.length === 1 && length === 0)) {
					this.$emit("reloadView");
				} else {
					if (this.$refs.menuTree) {
						this.$refs.menuTree.setActivedNode(node);
					}
				}
			}
		},
		getActiveKey() {
			this.$nextTick(() => {
				this.timer = setTimeout(() => {
					if (this.$refs.menuTree) {
						let nodeKey = this.$refs.menuTree.$refs.tree.getCurrentKey();
						console.log("当前选中菜单ID", nodeKey);
					}
				}, 500);
			});
		},
		showChildrenMenus() {
			this.lazyTreeRowId = "";
			this.showChildren = this.menuHandler.hasChildren(this.mainNode);
		},
		disabledNodeName(node) {
			if (this.envMode === "production") {
				return true;
			}
			return this.disabledIds.includes(node.id.toString());
		},
		disabledHasChildren(node) {
			if (this.envMode === "production") {
				return true;
			}
			return this.disabledIds.includes(node.id.toString()) || Number(node.level) !== 2;
		},
		disabledPermission(node) {
			return Number(this.user.permission) < 6;
		},
		disabledCommon(node) {
			return this.disabledIds.includes(node.id.toString());
		},
		showAppend(node, data) {
			return Number(node.level) !== 3 && data.id.toString() !== "1-1";
		},
		showRemove(node, data) {
			return !this.disabledIds.includes(data.id.toString()) && data.id.toString() !== "0";
		},
		allowDrag(draggingNode) {
			if (this.envMode === "production") {
				return false;
			}
			return !this.disabledIds.includes(draggingNode.data.id.toString());
		},
		allowDrop(draggingNode, dropNode, type) {
			//只有同级别可以拖曳放置
			return draggingNode.data.level === dropNode.data.level;
		},
		sortMenuId(parent, array) {
			array.forEach((item, index) => {
				item.id = parent ? parent.id + "-" + (index + 1) : (index + 1);
			});
		},
		handleSubmit() {
			this.mainNode.children = this.tableData;
			this.showChildren = false;
		},
		updateMenus(node) {
			this.menuArray = this.menuHandler.updateMenus(node, this.menuArray);
		},
		saveMenu() {
			if (!this.validate) {
				this.message.error("菜单名称不可重复，请重新输入新的菜单名！");
				return;
			}
			this.updateMenus(this.mainNode);
			//全量更新缓存数据
			this.vuex("menus", this.menuArray);
			// 同步刷新当前页面
			this.$emit("reloadView");
		},
		downloadMenu() {
			this.saveMenu();
			//正确无误的文件保存到本地
			if (this.validate) {
				this.resourceUtils.download(this.menuArray, "menus.json");
			}
		},
		//图标选择器在点击获取焦点后再显示所有可选图标，优化页面加载速度
		loadIcons() {
			this.options.ElementUI = true;
			this.options.FontAwesome = true;
			this.options.eIcon = true;
			this.options.eIconSymbol = true;
			this.options.addIconList = [];
			this.options.removeIconList = [];
		},
		loadTable(row, treeNode, resolve) {//每次懒加载只显示一行数据展开
			if (this.menuHandler.hasChildren(row)) {
				this.timer = setTimeout(() => {
					resolve(row.children);
				}, 200);
			}
		},
		expandChange(row, expanded) {
			let treeData = this.$refs.menusTable.store.states.treeData;
			if (this.lazyTreeRowId && treeData[this.lazyTreeRowId]) {
				console.log(this.lazyTreeRowId, expanded, treeData);
				treeData[this.lazyTreeRowId].expanded = false;
			}
			this.lazyTreeRowId = row.id.toString();
		},
		setPath(node) {
			node.path = node.hasChildren ? null : "";
			node.children = node.hasChildren ? [] : null;
		},
		setGroup(node) {
			if (Number(node.level) === 2 && this.menuHandler.hasChildren(node)) {
				node.children.forEach(child => {
					child.group = node.group;
				});
			}
		},
		createPath(node, event) {
			if (!node.name) {
				this.message.error("名称为不能为空，请输入菜单名！");
				return;
			}
			let menuId = this.menusNames[node.name];
			if (menuId && menuId !== node.id.toString()) {
				console.log(menuId);
				this.validate = false;
				this.message.error("此名称已使用，请重新输入新的菜单名！");
				return;
			}
			node.name = this.stringUtils.kebabCase(node.name).trim();
			node.titleEn = this.stringUtils.upperWordGroup(node.name).trim();
			if (node.path != null) {
				// 自动添加根菜单节点的名称作为 path 前缀
				let rootId = Number(node.id.toString().split("-")[0]);
				let menu = this.menuArray.filter(menu => Number(menu.id) === rootId)[0];
				node.path = "/" + menu.name + "/" + node.name;
			}
			this.validate = true;
		},
		setDifference(parent, current) {
			return Math.abs(Number(current.level) - Number(parent.level));
		},
		showSortUp(row) {
			const currentId = row.id.toString();
			if (currentId === "1-1" || currentId === "1-2") {
				return false;
			}
			const arr = this.stringUtils.toArray(currentId, "-");
			return Number(arr[arr.length - 1]) > 1;
		},
		showSortDown(row) {
			const currentId = row.id.toString();
			if (currentId === "1-1") {
				return false;
			}
			let parent = {};
			const arr = this.stringUtils.toArray(currentId, "-");
			let difference = this.setDifference(this.mainNode, row);
			if (difference === 2) {
				parent = this.mainNode.children.filter(item => item.id.toString() === (arr[0] + "-" + arr[1]))[0];
			} else {
				parent = this.mainNode;
			}
			let length = parent.hasChildren && parent.children.length;
			return Number(arr[arr.length - 1]) < Number(length);
		},
		sortRow(row, isUp) {
			let newId = this.getSortNewId(row, isUp);
			let newRow = this.getSortNewRow(row, newId);
			this.updateMenuId(row, newRow, row.id.toString(), newId);
		},
		getSortNewId(row, isUp) {
			let parentId = "";
			const arr = this.stringUtils.toArray(row.id.toString(), "-");
			const currentIndex = Number(arr[arr.length - 1]);
			let endIndex = isUp ? currentIndex - 1 : currentIndex + 1;
			let difference = this.setDifference(this.mainNode, row);
			if (difference === 2) {
				parentId = arr[0] + "-" + arr[1];
			} else {
				parentId = this.mainNode.id.toString();
			}
			return parentId + "-" + endIndex;
		},
		getSortNewRow(row, newId) {
			let parent = this.getRowParent(row);
			return parent.children.filter(child => child.id.toString() === newId)[0];
		},
		getRowParent(row) {
			const arr = this.stringUtils.toArray(row.id.toString(), "-");
			let difference = this.setDifference(this.mainNode, row);
			if (difference === 2) {
				return this.mainNode.children.filter(item => item.id.toString() === (arr[0] + "-" + arr[1]))[0];
			} else {
				return this.mainNode;
			}
		},
		updateMenuId(currRow, newRow, oldId, newId) {
			//更新当前
			this.updateRow(currRow, oldId, newId);
			//更新交换对象
			this.updateRow(newRow, newId, oldId);
			//同步刷新当前页面
			this.$emit("reloadView");
		},
		updateRow(row, target, src) {
			row.id = src;
			if (this.menuHandler.hasChildren(row)) {
				for (let child of row.children) {
					child.id = child.id.replace(target + "-", src + "-");
				}
			}
		},
		appendRow(row) {
			let parent = this.getRowParent(row);
			parent.children.push({
				id: parent.id + "-" + (parent.children.length + 1),
				name: "New Node",
				title: "新建节点",
				titleEn: "New Node",
				icon: "el-icon-s-data",
				group: "common",
				level: parent.level + 1,
				permission: 1,
				hasChildren: false,
				path: ""
			});
		},
		removeRow(row) {
			let parent = this.getRowParent(row);
			let rowIndex = parent.children.findIndex(d => d.id.toString() === row.id.toString());
			if (parent.level === 1 && rowIndex === 0) {
				return;
			}
			parent.children.splice(rowIndex, 1);
		}
	},
	beforeDestroy() {
		if (this.timer) {
			clearTimeout(this.timer); // 在Vue实例销毁前，清除我们的定时器
		}
	}
};
